layui.use(['layer','form','table'], function() {
    var layer = layui.layer, form = layui.form,table=layui.table;
    var id = getUrlParam('id');show_loading();
    $('.sel-load').selLoad(function () {
        form.render('select');
        $.post(rurl('scm/impOrderPayment/initApply'),{'id':id},function (res) {
           if(isSuccessWarnClose(res)){
                var data = res.data,payment=data.payment,members=data.members;
                form.val("mainForm",payment);
                $('#foreignCurrency').html(payment.currencyName);
                $('#goodsRateTime').html(payment.goodsRateTime);
                $('.exchangeRate').html(payment.exchangeRate);
               var ohtml = [];
               $.each(members || [],function (i,o){
                   ohtml.push('<tr>');
                   ohtml.push('<td class="t-a-c">'+(i+1)+'</td>');
                   ohtml.push('<td class="t-a-c"><a href="javascript:" class="'+o.statusId+'">'+o.statusDesc+'</a></td>');
                   ohtml.push('<td class="t-a-c">'+o.docNo+'</td>');
                   ohtml.push('<td class="t-a-c">'+o.orderDate+'</td>');
                   ohtml.push('<td>&nbsp;&nbsp;'+o.supplierName+'</td>');
                   ohtml.push('<td class="t-a-r" totalPrice="'+o.totalPrice+'">'+formatCurrency(o.totalPrice)+'&nbsp;&nbsp;</td>');
                   ohtml.push('<td class="t-a-c">'+o.currencyName+'</td>');
                   ohtml.push('<td class="t-a-r" applyPayVal="'+(Math.round((o.totalPrice - o.applyPayVal)*100)/100)+'">'+formatCurrency(o.totalPrice - o.applyPayVal)+'&nbsp;&nbsp;</td>');
                   ohtml.push('<td><input type="hidden" LIST name="orderId" value="'+o.id+'"/><input type="hidden" LIST name="orderNo" value="'+o.docNo+'"/><input type="text" LIST class="layui-input required" name="applyPayVal" onblur="calculationAll()" NUMBER value="'+(Math.round((o.totalPrice - o.applyPayVal)*100)/100)+'"/></td>');
                   ohtml.push('<td class="t-a-c"><a href="javascript:" onclick="deleteRow(this)"><i class="fa fa-trash-o"></i></a></td><td>&nbsp;</td></tr>');
               });
               $('#orderBody').html(ohtml.join(""));
               initInput();
               calculationAll();
           }
        });
    });

    $('#addSupplier').click(function () {
        var mid=parent.parent.obtainMIdByOperation('supplier_list'),taskArg={"documentId":"","documentClass":"","operation":""};
        if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
        var $payeeName = $('#payeeName'),params = {'customerName':$('#customerName').val()};
        if(!isEmpty($payeeName.val())){
            params['name'] = $payeeName.val();
        }
        setLocalStorage('TASK_'+mid,JSON.stringify(params));
        setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
        parent.parent.refreshTab(mid);
    });

    $('.auto-supplier-bank').autocomplete({
        source: function (request, response) {
            $.post(rurl('scm/supplierBank/vague'),{customerId:$('#customerId').val(),supplierName:$('#payeeName').val(),bankName: trim(request.term)},function (res) {
                response($.map(res.data, function (item) {return {label: item.name, value: item.name, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            var data = ui.item.data;
            form.val("mainForm",{'payeeBankAccountNo':data.account,'swiftCode':data.swiftCode,'ibankCode':data.ibankCode,'payeeBankAddress':data.address});
        }
    }).focus(function () {
        $(this).select().autocomplete("search");
    });

    $('.save-btn').click(function () {
        if(!checkedForm($('#mainForm'))){return;}
        if(!checkedForm($('#memberForm'))){return;}
        var orders = jsonList($('#memberForm').serializeJson());
        if(orders==null||orders.length==0){
            show_error("请至少选择一条订单信息进行付汇");return;
        }
        postJSON('scm/paymentAccount/apply',{'payment':$('#mainForm').serializeJson(),'orders':orders},function (res){
            prompt_success('申请成功',function () {
                var mid=parent.parent.obtainMIdByOperation('payment_list');
                if(!isEmpty(mid)){
                    parent.parent.refreshTab(mid);
                }
                parent.reloadList();
                closeThisWin();
            });

        });
    });

    form.on('radio(calculationFee)',function () {
        calculationFee();
    });

    $('#payeeName,#payeeBankName').blur(function () {
        calculationFee();
    })
});
function deleteRow(e) {
    confirm_inquiry("您确定要移除此订单？",function () {
        var $per = $(e).parent().parent();
        $per.remove();
        calculationAll();
    });
}
function calculationAll() {
    var ttotalPrice = 0.0,tpayVal = 0.0,rpayVal = 0.0;
    $.each($('td[totalPrice]'),function (i,o) {
        ttotalPrice += parseFloat($(o).attr('totalPrice'))
    })
    $.each($('td[applyPayVal]'),function (i,o) {
        tpayVal += parseFloat($(o).attr('applyPayVal'))
    })
    $.each($('input[name="applyPayVal"]'),function (i,o) {
        if(isEmpty($(o).val())){
            $(o).val('0');
        }
        rpayVal += parseFloat($(o).val())
    })
    $('.ttotalPrice').html(formatCurrency(ttotalPrice));
    $('.tpayVal').html(formatCurrency(tpayVal));
    $('.rpayVal').html(formatCurrency(rpayVal));
    $('#accountValue').val(formatCurrency(rpayVal));
    var payCny = formatCurrency(rpayVal*parseFloat($('#exchangeRate').val()));
    $('#accountValueCny').val(payCny);
    $('.payCny').html(payCny);
    calculationFee();
}
function calculationFee() {
    let counterFeeType = $('input[name="counterFeeType"]:checked').val(),swiftCode = $('#swiftCode').val(),
        paymentTerm=$('#paymentTerm').val(),orderId=getUrlParam('id').split(',')[0];
    $.get('/scm/paymentAccount/calculationFee',{
        paymentTerm:paymentTerm,
        counterFeeType:counterFeeType,
        swiftCode:swiftCode,
        orderId:orderId
    },function (res) {
        $('.bankFee').html(formatCurrency(res.data));
        $('.totalVal').html(formatCurrency(parseFloat($('#accountValueCny').val().replace(/,/g,''))+res.data));
    });
}